﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
using System.Data.SqlClient;
using System.IO;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public struct student
        {
            public int id;
            public string name;
            public string password;
            public string ssn;
            public string status;
            public string account;
            public string lastname;
            public string firstname;
            public string email;
            public int isadmin;

            public student(int id, string name, string password, string ssn, string status, string account, string lastname, string firstname, string email, int isadmin)
            {
                this.id = id;
                this.name = name;
                this.password = password;
                this.ssn = ssn;
                this.status = status;
                this.account = account;
                this.lastname = lastname;
                this.firstname = firstname;
                this.email = email;
                this.isadmin = isadmin;
            }
        }

        public struct kurs
        {
            public int id;
            public string code;
            public string name;

            public kurs(int id,string code,string name) 
            {
                this.id = id;
                this.code = code;
                this.name = name;
            }
        }

        public ServiceReference1.DatabaseClient test = new ServiceReference1.DatabaseClient();
        List<kurs> kurser = new List<kurs>();
        List<student> studenter = new List<student>();
        public Form1()
        {
            InitializeComponent();
            listBox1.Items.Clear();
            listBox2.Items.Clear();
            listBox3.Items.Clear();
        }
        public void Form1_Load(object sender, EventArgs e)
        {
            string[][] databaseInput = test.GetCourses();

            kurser.Clear();
            for (int i = 0; i < databaseInput.Length; i++)
            {
                kurser.Add(new kurs(int.Parse(databaseInput[i][0]), databaseInput[i][1], databaseInput[i][2]));
            }
            listBox1.Items.Clear();
            foreach (kurs k in kurser)
            {
                listBox1.Items.Add(k.code.Trim() + "\t" + k.name);
            }

        }

        public void updateListBox3()
        {
            listBox3.Items.Clear();
            if (listBox2.SelectedItem != null)
            {
                addNewTask_btn.Enabled = true;
                deleteTask_btn.Enabled = false;
                string code = listBox2.SelectedItem.ToString();
                string[] words = code.Split('\t');
                code = words[0].Trim();

                string[][] databaseInput = test.GetTasks(code);

                for (int i = 0; i < databaseInput.Length; i++)
                {
                    listBox3.Items.Add(databaseInput[i][0].ToString().Trim() + "\t" + databaseInput[i][1].ToString().Trim());
                }
            }
        }

        private void refreshGUI()
        {
            listBox1.Items.Clear();
            listBox2.Items.Clear();
            listBox3.Items.Clear();
            listBox1_SelectedIndexChanged(this, null);
            listBox2_SelectedIndexChanged(this, null);
            listBox3_SelectedIndexChanged(this, null);
            Form1_Load(this, null);
        }

        private void search_txt_TextChanged(object sender, EventArgs e)
        {
            listBox1.Items.Clear();

            string searchString = search_txt.Text;
            string spattern = "*" + search_txt.Text + "*";

            foreach (kurs k in kurser)
            {
                if (k.name.ToLower().Contains(searchString.ToLower()) || k.code.Contains(searchString))
                //if (System.Text.RegularExpressions.Regex.IsMatch(k.name,spattern,System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                {
                    listBox1.Items.Add(k.code.Trim() + "\t" + k.name);

                }

            }
        }
        private void search2_txt_TextChanged(object sender, EventArgs e)
        {
            kurser_box.Items.Clear();
            kurser_box.Items.Add("<ALLA ELEVER>");

            string searchString = search2_txt.Text;
            string spattern = "*" + search2_txt.Text + "*";

            foreach (kurs k in kurser)
            {
                if (k.name.ToLower().Contains(searchString.ToLower()) || k.code.Contains(searchString))
                //if (System.Text.RegularExpressions.Regex.IsMatch(k.name,spattern,System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                {
                    kurser_box.Items.Add(k.code.Trim() + "\t" + k.name);
                }
            }
        }
        private void search3_txt_TextChanged(object sender, EventArgs e)
        {
            elev_table.Rows.Clear();
            string searchString = search3_txt.Text;
            string spattern = "*" + search3_txt.Text + "*";

            foreach (student s in studenter)
            {
                if (s.name.ToLower().Contains(searchString.ToLower()) || s.account.Contains(searchString))
                //if (System.Text.RegularExpressions.Regex.IsMatch(k.name,spattern,System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                {
                    elev_table.Rows.Add(s.name, s.ssn, s.account, s.email);
                }
            }
        }

#region listbox_SelectedIndexChanged
        public void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox1.SelectedItem != null)
            {
                listBox2.Items.Clear();
                listBox3.Items.Clear();
                addNewTask_btn.Enabled = false;
                deleteTask_btn.Enabled = false;
                string code = listBox1.SelectedItem.ToString();
                string[] words = code.Split('\t');
                code = words[0].Trim();

                string[][] databaseInput = test.GetTaskGroups(code);


                for (int i = 0; i < databaseInput.Length; i++)
                {
                    listBox2.Items.Add(databaseInput[i][0].ToString().Trim() + "\t" + databaseInput[i][1].ToString().Trim());
                }
            }
        }

        public void listBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            updateListBox3();
        }

        public void listBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox3.SelectedItem != null)
            {
                deleteTask_btn.Enabled = true;
            }
        }

        private void kurser_box_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (kurser_box.SelectedItem != null)
            {
                string code = kurser_box.SelectedItem.ToString();
                string[] words = code.Split('\t');

                //fulhax för att kunna få ut alla elever: <ALLA ELEVER> är hårdkodad i Elever_tab_enter()
                string[][] databaseInput;
                if (code == "<ALLA ELEVER>")
                {
                    databaseInput = test.GetUsers();
                }
                else
                {
                    code = words[0].Trim();
                    databaseInput = test.GetUsersFromCourse(code);
                }
                

                studenter.Clear();
                for (int i = 0; i < databaseInput.Length; i++)
                {
                    studenter.Add(new student(int.Parse(databaseInput[i][0]), databaseInput[i][1],databaseInput[i][2], databaseInput[i][3], databaseInput[i][4], databaseInput[i][5], databaseInput[i][6], databaseInput[i][7], databaseInput[i][8], int.Parse(databaseInput[i][9])));
                }
                elev_table.Rows.Clear();
                foreach (student s in studenter)
                {
                    elev_table.Rows.Add(s.name,s.ssn,s.account,s.email);
                }
            }
        }

#endregion

        private void addNewTask_btn_Click(object sender, EventArgs e)
        {
            //ADD new Task!
            if (listBox2.SelectedItem != null)
            {
                string id = listBox2.SelectedItem.ToString();
                string[] words = id.Split('\t');
                id = words[0].Trim();

                addNewTaskForm inputBox = new addNewTaskForm(int.Parse(id),test,this);
                inputBox.Show();
                listBox2.Refresh();
            }
        }

        private void deleteTask_btn_Click(object sender, EventArgs e)
        {
            //Remove Task!
            if (listBox2.SelectedItem != null)
            {
                string id = listBox3.SelectedItem.ToString();
                string[] words = id.Split('\t');
                id = words[0].Trim();

                string error = test.removeTask(int.Parse(id));

                if (error != "" || error.Length > 1)
                {
                    System.Windows.Forms.MessageBox.Show("ID: '" + id + "'" + "; Error: '" + error + "'");
                }
                updateListBox3();
            }

        }

        private void addNewCourse_btn_Click(object sender, EventArgs e)
        {
            //ADD new Course!
            if (listBox1.SelectedItem != null)
            {
                string code = listBox1.SelectedItem.ToString();
                string[] words = code.Split('\t');
                code = words[0].Trim();
            }
                
            addNewCourseForm inputBox = new addNewCourseForm(test, this);
            inputBox.Show();
            listBox1.Refresh();
        }

        private void deleteCourse_btn_Click(object sender, EventArgs e)
        {
            //Remove Course!
            if (listBox1.SelectedItem != null)
            {
                string Code = listBox1.SelectedItem.ToString();
                string[] words = Code.Split('\t');
                Code = words[0].Trim();

                //Console.WriteLine("Code: '"+Code+"'");
                string error = test.removeCourse(Code);

                if (error != "" || error.Length > 1)
                {
                    System.Windows.Forms.MessageBox.Show("Code: '" + Code + "'" + "; Error: '" + error+"'");
                }
                refreshGUI();
            }

        }

        public void readFileAndInsertUsersToDB()
        {
            List<student> studenter = new List<student>();
            string filePath = @"C:\Users\LURKEN\Documents\My Dropbox\shared 2\CSharp\exData.txt";
            string line;
            string wholeName;
            string account;

            if (File.Exists(filePath))
            {
                StreamReader file = null;
                try
                {
                    Console.WriteLine("läser filen");
                    int i = 0;
                    file = new StreamReader(filePath);
                    while ((line = file.ReadLine()) != null)
                    {
                        Console.WriteLine("     en student");
                        line = line.Replace("\"","");
                        line = line.Replace(" ","");
                        string[] lines = line.Split(',');

                        wholeName = lines[5].Replace("\'","").ToString()+" "+lines[4].Replace("\'","").ToString();
                        account = lines[5].Replace("\'","").Substring(0,2).ToString()+lines[4].Replace("\'","").Substring(0,2).ToString(); 

                        studenter.Add(new student(i,wholeName,lines[3].ToString(),lines[1].Replace("-","").ToString(),"status",account,lines[5].ToString(),lines[4].ToString(),lines[6].Replace(")","").ToString(),0));
                    
                        i++;
                    }

                    Console.WriteLine("Börjar skriva till DB:");
                    foreach (student s in studenter) 
                    {
                        test.AddUser(1, s.name, s.password, s.ssn, s.status, s.account, s.lastname, s.firstname, s.email, s.isadmin);
                        Console.WriteLine(s.id+" "+ s.name+" "+ s.password+" "+ s.ssn+" "+ s.status+" "+ s.account+" "+ s.lastname+" "+ s.firstname+" "+ s.email+" "+ s.isadmin);
                    }
                }
                finally
                {
                    if (file != null)
                        file.Close();
                }
            }
        }

        public void addUsersToManyCourses()
        {
            int antalUsers = test.GetUsers().Length;
            int antalKurser = test.GetCourses().Length;
            string error;
            error = "";

            Console.WriteLine("antalUsers:"+antalUsers);
            Console.WriteLine("antalKurser:"+antalKurser);

            ////addar alla till första kursen
            //for (int i = 0; i < antalUsers; i++)
            //{
            //    Console.WriteLine("Adding user: "+i+" to course:0");
            //    error =  test.AddUsersToCourse(i, 0, 1, 0);
            //    Console.WriteLine(error);
            //}

            //for (int i = 0; i < antalUsers; i++)
            //{

            //    if (i % 2 == 0)
            //    {
            //        Console.WriteLine("Adding user: " + i + " to course:1");
            //        error = test.AddUsersToCourse(i, 1, 1, 0);
            //        Console.WriteLine(error);
            //    }
            //}

            //for (int i = 0; i < antalUsers; i++)
            //{

            //    if (i % 3 == 0)
            //    {
            //        Console.WriteLine("Adding user: " + i + " to course:3");
            //        test.AddUsersToCourse(i, 3, 1, 0);
            //        Console.WriteLine(error);
            //    }
            //}
            /*
            for (int i = 0; i < antalUsers; i++)
            {
                if (i % 4 == 0)
                {
                    Console.WriteLine("adding user: " + i + " to course:4");
                    test.AddUsersToCourse(i, 4, 1, 0);
                    Console.WriteLine(error);
                }
            }
            
            for (int i = 0; i < antalUsers; i++)
            {
                if (i % 5 == 0)
                {
                    Console.WriteLine("adding user: " + i + " to course:5");
                    test.AddUsersToCourse(i, 5, 1, 0);
                    Console.WriteLine(error);
                }
            }

            for (int i = 0; i < antalUsers; i++)
            {
                if (i % 6 == 0)
                {
                    Console.WriteLine("adding user: " + i + " to course:6");
                    test.AddUsersToCourse(i, 6, 1, 0);
                    Console.WriteLine(error);
                }
            }

            for (int i = 0; i < antalUsers; i++)
            {
                if (i % 7 == 0)
                {
                    Console.WriteLine("adding user: " + i + " to course:7");
                    test.AddUsersToCourse(i, 7, 1, 0);
                    Console.WriteLine(error);
                }
            }

            for (int i = 0; i < antalUsers; i++)
            {
                if (i % 8 == 0)
                {
                    Console.WriteLine("adding user: " + i + " to course:8");
                    test.AddUsersToCourse(i, 8, 1, 0);
                    Console.WriteLine(error);
                }
            }

            for (int i = 0; i < antalUsers; i++)
            {
                if (i % 9 == 0)
                {
                    Console.WriteLine("adding user: " + i + " to course:9");
                    test.AddUsersToCourse(i, 9, 1, 0);
                    Console.WriteLine(error);
                }
            }
            for (int i = 0; i < antalUsers; i++)
            {
                if (i % 10 == 0)
                {
                    Console.WriteLine("adding user: " + i + " to course:10");
                    test.AddUsersToCourse(i, 10, 1, 0);
                    Console.WriteLine(error);
                }
            }
            
            */
        }


        private void button1_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.MessageBox.Show("Sa ju åt dig att inte klicka! Hade jag inte kommenterat bort EN rad så hade du precis förstört databasen!");
            addUsersToManyCourses();
            //readFileAndInsertUsersToDB();
        }

        private void Elever_tab_enter(object sender, EventArgs e)
        {
            kurser_box.Items.Clear();
            kurser_box.Items.Add("<ALLA ELEVER>");
            foreach (kurs k in kurser)
            {
                kurser_box.Items.Add(k.code.Trim() + "\t" + k.name);
            }
        }

        private void Elever_tab_Leave(object sender, EventArgs e)
        {
            elev_table.Rows.Clear();
        }

        private void elev_table_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            //här kan man lägga kod om man vill få upp ett nytt fönster med eleven!
            
            if (elev_table.CurrentCell.Value != null)
            {
                Console.WriteLine(elev_table.CurrentCell.Value.ToString());

                string code = elev_table.CurrentRow.Cells.ToString();
                string[] words = code.Split('\t');
                code = words[0].Trim();

                studentForm sForm = new studentForm(studenter[elev_table.CurrentCell.RowIndex]);
                sForm.Show();
            }
        }
    }
}
